<?php

namespace App\BO\Order;

use App\BO\Order\CreateOrder\CreateOrderFactory;
use App\BO\Order\CreateOrder\CreateOrderInfo;
use App\Entities\AreaEntity;
use App\Entities\CouponCodeEntity;
use App\Entities\UserAddressEntity;
use App\Entities\UserCouponEntity;
use App\Entities\UserEntity;
use App\Meta\OrderPeriodDate;
use App\ServicesNew\CartService;
use App\Utils\Assert;
use Carbon\Carbon;

class CreateOrderItemFactory
{
    /**
     * @return CartService
     */
    protected static function getCartService()
    {
        return app(CartService::class);
    }

    /**
     * @param CreateOrderInfo $createOrderInfo
     * @return CreateOrderItem
     * @throws \Exception
     */
    public static function getByCreateOrderInfo(CreateOrderInfo $createOrderInfo)
    {
        $createOrderItem = new CreateOrderItem();

        $createOrderItem->setUserEntity(UserEntity::find($createOrderInfo->getUserId()));

        // 购物车信息
        $cartItemEntity = self::getCartService()->getCartItemEntityByUserId($createOrderInfo->getUserId());
        Assert::notNull($cartItemEntity);
        $createOrderItem->setCartItemEntity($cartItemEntity);

        // 商品信息
        $createOrderItem->setProduct(CreateOrderFactory::getProductInfoByCartItemEntity($cartItemEntity));

        // 用户当前城市
        $areaEntity = AreaEntity::find($createOrderInfo->getCityId());
        Assert::notNull($areaEntity);
        $createOrderItem->setCurrentAddress($areaEntity);

        // 地址信息
        $userAddressEntity = UserAddressEntity::find($createOrderInfo->getAddressId());
        Assert::notNull($userAddressEntity);
        $createOrderItem->setOrderAddress($userAddressEntity);

        // 是否使用余额
        $createOrderItem->setUseBalance($createOrderInfo->getUserBalance());

        // 优惠券信息
        $couponId = $createOrderInfo->getUserCouponId();
        if ($couponId > 0) {
            $createOrderItem->setUseCoupon(true);

            $couponCodeEntity = CouponCodeEntity::find($couponId);
            Assert::notNull($couponCodeEntity);

            $userCouponEntity = UserCouponEntity::findByCouponId($couponId);
            Assert::notNull($userCouponEntity);

            $createOrderItem->setUserCouponEntity($userCouponEntity);
            $createOrderItem->setCouponEntity($couponCodeEntity);
        }

        // 服务时间逻辑
        $orderPeriodDate = new OrderPeriodDate();
        $orderPeriodDate->setDate(Carbon::parse($createOrderInfo->getAssignDate())->toDateString());
        $orderPeriodDate->setTimePeriodId($createOrderInfo->getAssignTime());

        $createOrderItem->setServiceDate($orderPeriodDate);

        // 备注信息
        $createOrderItem->setRemark($createOrderInfo->getRemark());

        return $createOrderItem;
    }
}
